package com.example.server.util;


import com.example.server.bean.FastDFSFile;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * ProjectName: FastDFS-demo
 * Author: 别怿言
 * Date: 2023-02-17 22:38
 * Description：FastDFS工具类
 */
public class FastDFSUtil {

    private static Logger logger = LoggerFactory.getLogger(FastDFSUtil.class);

    //ClientGlobal.init 读取配置文件初始化配置
    static {
        try {
            String filepath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            ClientGlobal.init(filepath);
        } catch (Exception e) {
            logger.error("FastDFS Client Init Fail!",e);
        }
    }

    public static String[] upload(MultipartFile file){
        String filename = file.getOriginalFilename();
        String author = "byy";
        String ext = filename.substring(filename.lastIndexOf(".")+1);
        logger.info("File Name:"+filename+ "File type:"+ext);
        NameValuePair[] meta_list = new NameValuePair[1];
        meta_list[0] = new NameValuePair("author", author);

        long start = System.currentTimeMillis();
        String[] uploadResults = null;
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            uploadResults = storageClient.upload_file(file.getBytes(), ext, meta_list);
        } catch (Exception e) {
            logger.error("上传失败，File Name："+file.getName(),e);
        }
        logger.info("上传时间:"+(System.currentTimeMillis()-start)+"ms");
        //验证结果
        if(uploadResults==null&&storageClient!=null){
            logger.error("上传失败 "+storageClient.getErrorCode());
        }
        logger.info("上传成功，group_name:"+uploadResults[0]+",remoteFilename"+uploadResults[1]);
        return uploadResults;
    }

    public static InputStream download(String groupName,String remoteFileName){
        try {
            StorageClient storageClient = getStorageClient();
            byte[] filebyte = storageClient.download_file(groupName, remoteFileName);
            InputStream ins = new ByteArrayInputStream(filebyte);
        } catch (Exception e) {
            logger.error("下载失败",e);
        }
        return null;
    }

    public static void delete(String groupName,String remoteFileName){
        try {
            StorageClient storageClient = getStorageClient();
            int i = storageClient.delete_file(groupName, remoteFileName);
            logger.info("删除成功"+i);
        } catch (Exception e) {
            logger.error("删除失败",e);
        }
    }

    public static FileInfo getfileinfo(String groupName, String remoteFileName){
        try {
            StorageClient storageClient = getStorageClient();
            FileInfo file_info = storageClient.get_file_info(groupName, remoteFileName);
            return file_info;
        } catch (Exception e) {
            logger.error("查看文件信息失败",e);
        }
        return null;
    }

    public static String getTrackerurl() throws Exception{
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getTrackerServer();
        StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
        return "http://"+storeStorage.getInetSocketAddress().getHostString()+":8888/";
    }

    /**
     *生成Storage客户端
     * @return StorageClient
     */
    private static StorageClient getStorageClient() throws IOException {
        TrackerServer trackerServer = getTrackerServer();
        return new StorageClient(trackerServer,null);
    }

    /**
     *生成Tracker服务器端
     * @return TrackerServer
     */
    private static TrackerServer getTrackerServer() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        return trackerClient.getTrackerServer();
    }

}
